<template>
  <!-- 提现审核页面 -->
  <div class="app-container">
    <el-form ref="queryForm" :inline="true" :model="queryForm">
      <!-- <el-form-item label="名字" prop="userRealName">
        <el-input
          v-model="queryForm.userRealName"
          size="small"
          placeholder="请输入用户真实名字"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="买家选择框">
          <el-select v-model="queryForm.userId" clearable filterable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.mobile"
              :label="item.mobile + '-' + item.userRealName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="queryForm.status" @change="changeStatus" clearable filterable placeholder="请选择">
            <el-option
              v-for="(item,index) in statusList"
              :key="item"
              :label="item"
              :value="index"
            />
          </el-select>
        </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <!-- <el-form-item label="买家选择框">
          <el-select v-model="formModel.buyerId" @change="changePeople" filterable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.id + '-' + item.userRealName"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          :loading="loadingDown"
          size="mini"
          @click="handleDownLoad"
        >下载提现记录</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
        <div class="tixian">
          <span>当日申请提现总额：</span>
          <span style="color: #ef3939;">￥{{ tixian }}</span>
        </div>
        <div class="tixian">
          <span>剩余可提现总额：</span>
          <span style="color: #ef3939;">￥{{ elses }}</span>
        </div>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      border
      :data="orderList"
      style="width: 100%"
      @sort-change="handleSortChange"
    >
      <el-table-column align="center" label="id" prop="id" width="60" />
      <el-table-column align="center" label="用户ID" prop="userId" width="100" />
      <el-table-column align="center" label="真实姓名" prop="creater" width="100" />
      <!--  -->
      <el-table-column
        align="center"
        min-width="100"
        label="手机号"
        prop="mobile"
        width="200"
      />
      <!-- <el-table-column align="center" label="当前账户可提现金额" prop="userWithdrawalAmount" width="300" /> -->
      <el-table-column align="center" label="提现金额" prop="amount" min-width="100" />
      <el-table-column align="center" label="手续费" prop="commission" min-width="100" />
      <el-table-column align="center" label="实际到账金额" prop="actualReceivedAmount" min-width="200" />

      <el-table-column align="center" label="申请时间" prop="createTime" min-width="300" />
      <el-table-column align="center" label="状态" prop="status" min-width="100">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.status === 0?'待审核': scope.row.status === 1? '已同意' : '已拒绝' }}</el-tag>

        </template>
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template v-if="scope.row.status === 0" slot-scope="scope">
          <el-button
            size="mini"
            @click="handleRefund(scope.row)"
          >审核通过</el-button>
          <el-button
            size="mini"
            @click="handleCancelOrder(scope.row)"
          >拒绝</el-button>  
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total"
      :total="total"
      :page.sync="queryForm.pageNum"
      :limit.sync="queryForm.pageSize"
      @pagination="getList"
    />

    <el-dialog :visible.sync="showOrderVisible" title="指定用户">
      <el-form ref="formRef" :model="formModel">
        <el-form-item label="买家选择框">
          <el-select v-model="formModel.buyerId" filterable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.mobile"
              :label="item.mobile + '-' + item.userRealName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showOrderVisible = false">取 消</el-button>
        <el-button type="primary" @click="onConfirm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  delOrder,
  getOrder,
  refundOrder,
  getTodayData,
  listChannel,
  clickShip, splitOrderReq, listUser, updateSaleStatus, downloadToday
} from '@/api/shop/order'
import { getWthdrawalList, wthdrawalExamine,getuserwthdrawalSum,exporUserwthdrawalrecordsList } from '@/api/shop/user/member'
import { yuan } from '@/utils'
import {excelNameDate} from  '@/utils/index'

const statuss = {
  0: '待审核',
  1: '同意提现',
  2: '已拒绝'
}
export default {
  name: 'AdjOrderList',
  filters: {
    yuan
  },
  data() {
    return {
      loading: true,
      shenqing:0,
      elses:0,
      // 列表总数
      total: 0,
      // 日期范围
      dateRange: [],
      totalBuy: 10000,
      totalSale: 11000,
      totalIncome: 0,
      // 订单状态数据字典
      orderStatusOptions: [],
      payTypeOptions: [
        { name: '微信', value: '1' },
        { name: '支付宝', value: '2' },
        { name: '测试', value: '3' }
      ],
      statusList : ['待审核','同意提现','已拒绝'],
      // 查询参数
      queryForm: {
        pageNum: 1,
        pageSize: 10,
        orderSn: undefined,
        userId: undefined,
        name: undefined,
        status:null
      },
      // 角色列表
      orderList: [],
      orderDialogVisible: false,
      orderDetail: {
        order: {},
        user: {},
        orderGoods: []
      },
      channels: [],
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined
      },
      shipFormRules: {
        shipChannel: [
          { required: true, message: '发货渠道不能为空', trigger: 'blur' }
        ],
        shipSn: [
          { required: true, message: '发货编号不能为空', trigger: 'blur' }
        ]
      },
      shipDialogVisible: false,
      showOrderVisible: false,
      formModel: {
        tableData: []
      },
      options: [],
      loadingDown: false
    }
  },
  created() {
    this.getOptions()
    this.getList()
    this.getuserwthdrawal()
    // this.getChannel()
  },
  methods: {
    changeStatus(val){
      console.log(val)
      this.$set(this.formModel,'status',val)
    },
    async getuserwthdrawal(){
      const res = await getuserwthdrawalSum()
      if(res.code == 200){
        this.tixian = res.map.applyWithdrawalPrice
        this.elses = res.map.ktxPrice
      }
    },

    // 获取买家
    async getOptions() {
      const {
        map: { userList }
      } = await listUser()
      this.options = userList
    },
    async onConfirm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) {
          return
        }
        await splitOrderReq({ ...this.formModel })
        this.$message.success('操作成功')
        this.formModel = {}
        this.$refs.formRef.resetFields()
        this.getList()
        this.showOrderVisible = false
      })
    },
    handleOrder(record) {
      this.formModel.orderId = record.id
      this.showOrderVisible = true
    },
    handleStatus(record) {
      updateSaleStatus({ 'orderId': record.id }).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功')
        } else {
          this.$message.error('操作失败')
        }
        this.getList()
      })
    },
    getChannel() {
      listChannel().then((response) => {
        this.channels = response.map.data
      })
    },
    handleQuery() {
      this.orderList = []
      this.getList()
    },
    /**
           * 表单重置
           */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.dateRange = []
      this.handleQuery()
    },
    async getList() {
      console.log(this.queryForm)
      const {
        map: {
          page: { records: data, total }
          // page: data
        }
      } = await getWthdrawalList({ ...this.queryForm, timeStr: this.dateRange && this.dateRange.length ? `${this.dateRange[0]},${this.dateRange[1]}` : '' })
      this.total = total
      this.orderList = data
      console.log(this.orderList)
      this.loading = false
    },
    /**
           * 后端排序
           */
    handleSortChange(sort) {
      this.queryForm.sortName = sort.prop
      this.queryForm.sortOrder = sort.order
      console.log(sort)
      this.getList()
    },
    async handleDetail(row) {
      const {
        map: { data }
      } = await getOrder(row.id)
      this.orderDetail = data
      this.orderDialogVisible = true
    },
    handleShip(row) {
      this.shipForm = {
        orderId: row.id,
        shipChannel: undefined,
        shipSn: undefined
      }
      this.shipDialogVisible = true
    },
    clickShip(row) {
      this.$refs['shipForm'].validate(async(valid) => {
        if (valid) {
          const { code, msg } = await clickShip(this.shipForm)
          if (code === 200) {
            this.$message.success('发货成功')
            this.shipDialogVisible = false
            this.getList()
          } else {
            this.$message.error(msg)
          }
        }
      })
    },
    // 审核通过
    handleRefund(row) {
      this.$confirm(
        '是否同意编号为 [' + row.id + '] 的提现订单?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          const data = row
          data.status = 1
          return wthdrawalExamine(data)
        })
        .then(() => {
          this.getList()
          this.$message.success('状态修改成功，请及时去工新云转账')
        })
        .catch(function(e) {})
    },
    // 审核拒绝
    handleCancelOrder(row) {
      this.$confirm(
        '是否拒绝编号为 [' + row.id + '] 的提现订单?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          const data = row
          data.status = 2
          return wthdrawalExamine(data)
        })
        .then(() => {
          this.getList()
          this.$message.success('已拒绝')
        })
    },
    /**
           * 删除按钮
           */
    async handleDelete(row) {
      const orderId = row.id
      this.$confirm(
        '是否确认删除订单编号为 [' + row.orderSn + '] 的订单吗?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delOrder(orderId)
        })
        .then(() => {
          this.getList()
          this.$message.success('删除成功')
        })
        .catch(function(e) {})
    },
    handleDownLoad() {
      this.$confirm(
        '是否下载提现记录',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
      )
        .then(res => {
          const data = {
            timeStr:this.dateRange && this.dateRange.length ? `${this.dateRange[0]},${this.dateRange[1]}` : '',
            status:this.queryForm.status
          }
          exporUserwthdrawalrecordsList(data).then(res => {
            const blob = new Blob([res.data], { type: 'application/msword' })// new Blob([res])中不加data就会返回下图中[objece objece]内容（少取一层）
            console.log(blob)
            let status = ''
            if(this.queryForm.status == null){
              status = '全部'
            }else{
              status = this.statusList[this.queryForm.status]
            }
            let times = this.dateRange && this.dateRange.length ? this.dateRange.join(" -") : ''
            const fileName = `提现数据${times}${status}.xls`// 下载文件名称
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
          })
          // this.loadingDown = true
          console.log(res)
        })
    }
  }
}
</script>
      <style lang="scss" scoped>
      .more_btn{
        margin-left: 10px;
      }
      .tixian{
        display: inline-block;
        margin-left: 50px
      }
      </style>
